﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RemotingGraphServer.cs" company="">
//   
// </copyright>
// <summary>
//   The remoting graph server.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using Systemathics.FrameWork.Interfaces;

namespace Systemathics.FrameWork
{
    [Serializable]
    public sealed class RemotingGraphServer 
    {
        private Graph Graph;
        public bool isListenning {get; private set;}

        public RemotingGraphServer(String serverName, Object strategyIdORSerieName)
        {
            try
            {
                var serverProv = new BinaryServerFormatterSinkProvider();
                serverProv.TypeFilterLevel = TypeFilterLevel.Full;
                var clientProv = new BinaryClientFormatterSinkProvider();

                var properties = new Hashtable();
                properties["portName"] = serverName;// "GraphServer";HistoryGraphServer;
                properties["exclusiveAddressUse"] = "false";
                var ipc = new IpcChannel(properties, clientProv, serverProv);
                ChannelServices.RegisterChannel(ipc, false);
                var portName = strategyIdORSerieName.ToString() + ".rem";
                var adress = "ipc://" + serverName + "/" + portName;
                RemotingConfiguration.RegisterWellKnownServiceType(typeof (Graph), portName, WellKnownObjectMode.Singleton);

                Graph = (Graph)Activator.GetObject(typeof(Graph), adress);
                isListenning = true;
            }
            catch (Exception)
            {
                isListenning = false;
            }
        }

        public Graph GetGraph
        {
            get { return Graph; }
        }
    }

    public class Graph : MarshalByRefObject, IGraph
    {
        #region IGraph Members

        public void Draw(GraphEventArgs message)
        {
            if (OnGraphRepaint != null && OnGraphRepaint.GetInvocationList().Length > 0)
                OnGraphRepaint(this, message);
        }

        public void DrawHidtory(GraphEventArgs message)
        {
            if (OnGraphRepaintHistory != null && OnGraphRepaintHistory.GetInvocationList().Length > 0)
                OnGraphRepaintHistory(this, message);
        }

        #endregion

        public event EventHandler<GraphEventArgs> OnGraphRepaint;
        public event EventHandler<GraphEventArgs> OnGraphRepaintHistory;

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}